import React, { Component } from 'react'
import shortid from 'shortid'
import store from './store'

class CommentsBox extends Component {
  constructor(props) {
    super(props)
    this.state = {
      text: ''
    }
    this.onChanges = this.onChanges.bind(this)
    this.submitInfo = this.submitInfo.bind(this)
  }

  //e.preventDefault 阻止默认行为
  submitInfo(e) {
    e.preventDefault()
    const { text } = this.state
    const id = shortid()
    const comments = {
      id,
      text
    }

    store.dispatch({ type: 'RRRR', comments })

    this.setState({
      text: ''
    })
  }

  //e.target.value 获取input值
  onChanges(e) {
    e.preventDefault()
    this.setState({
      text: e.target.value
    })
  }

  render() {
    const CForm = (
      <div>
        <input value={this.state.text} onChange={this.onChanges} />
        <button onClick={this.submitInfo}>提交</button>
      </div>
    )
    const rComments = store.getState()
    const CView = rComments.map(t => <div key={t.id}>{t.text}</div>)

    return (
      <div>
        {CForm}
        {CView}
      </div>
    )
  }
}

export default CommentsBox
